package com.adapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class FileDownloader extends Thread {
	String _urlStr;//下载文件
	File _fileSave;//目标文件
	Handler _myHandler;
	
	public FileDownloader(String urlStr,File file,Handler myHandler)
	{
		_urlStr = urlStr;
		_fileSave = file;
		_myHandler = myHandler;
	}
	
	@Override
	public void run() {
		if(_fileSave.exists())
		{
			_fileSave.delete();
		}
		try {
		    URL url = new URL(_urlStr);    
		    URLConnection con = url.openConnection(); 
		    int contentLength = con.getContentLength();
		    System.out.println("下载文件大小:"+contentLength);
//		    System.out.println("mList的大小："+mList.size());
		    InputStream is = con.getInputStream();   
		    int hasRead = 0; //
		    int progress = 0;
		    byte[] bs = new byte[128];    
		    int len;    
		    OutputStream os = new FileOutputStream(_fileSave.getPath());    
		    while ((len = is.read(bs)) != -1) {
		      os.write(bs, 0, len); 
		      hasRead +=len;
		      progress = (int)((double)hasRead/(double)contentLength * 100);//
		      Message msg = _myHandler.obtainMessage();
		      msg.arg1 = progress;
		      msg.sendToTarget();
		    }
		    os.close();   
		    is.close(); 
		} catch (Exception e) {
				e.printStackTrace();
		}
	}
}
